<template>
  <div id="structuralRisk">
    <!-- 输入框和按钮 -->
    <div class="search-container">
      <h3 class="search-title">风险模拟</h3>
      <div class="search-input">
        模拟节点：
        <el-input v-model="startNode" placeholder="请输入节点"  class="input"/>
      </div>
      <div class="search-input">
        一级指标：
        <el-select v-model="firstLevelRisk" placeholder="选择一级风险" class="input" @change="handleFirstLevelChange" >
          <el-option
            v-for="(option, index) in firstLevelOptions"
            :key="index"
            :label="option.label"
            :value="option.value"
          ></el-option>
        </el-select>
      </div>
      <div class="search-input">
        二级指标：
        <el-select  v-model="secondLevelRisk" placeholder="选择二级风险" class="input">
          <el-option
            v-for="(option, index) in secondLevelOptions"
            :key="index"
            :label="option.label"
            :value="option.value"
          ></el-option>
        </el-select>
      </div>
      <div class="search-button">
        <el-button type="primary" style="padding: 10px 30px; font-size: 18px;" @click="showAnalysisResults">风险模拟</el-button>
      </div>
    </div>

    <!-- 显示分析结果 -->
    <div v-if="showResults">
      <!-- 风险传导分析结果 -->
      <div class="analysis-info">
        <h3 class="title">风险传导分析结果</h3>
        <el-card class="risk-card">
          <div v-for="(risk, index) in riskAnalysis" :key="index" class="risk-item">
            <el-tag :type="risk.level">{{ risk.type }}</el-tag>
            <div class="risk-description">{{ risk.description }}</div>
          </div>
        </el-card>
      </div>

      <!-- 供应链路分析结果 -->
      <div class="analysis-info">
        <h3 class="title">供应链路分析结果</h3>
        <el-card class="path-card">
          <div v-for="(path, index) in pathAnalysis" :key="index" class="path-item">
            <div class="path-header">链路 {{ index + 1 }}</div>
            <div class="path-content">{{ path.description }}</div>
            <div class="path-metrics">
              <el-tag size="small">长度: {{ path.length }}</el-tag>
              <el-tag size="small" type="success">可靠度: {{ path.reliability }}</el-tag>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import {mapActions} from "vuex";
import axios from 'axios'; // 引入axios用于API请求

export default {
  name: 'StructuralRisk',
  data() {
    return {
      riskData: {
        startNode: '',
        failedEnterprises: []
      },
      startNode: '', // 起始企业
      showResults: false, // 是否显示结果
      firstLevelRisk: '',
      secondLevelRisk: '',
      projectId:'',
      // 新增：请求状态和错误信息
      firstLevelOptions: [
        { label: '结构风险', value: 'structuralRisk' },
        { label: '运行风险', value: 'operationalRisk' },
        { label: '环境风险', value: 'environmentalRisk' }
      ],
      secondLevelOptions: [],
      riskAnalysis: [
        {
          type: '供应链断裂风险',
          level: 'danger',
          description: '存在关键节点依赖，断裂风险较高'
        },
        {
          type: '质量风险',
          level: 'warning',
          description: '原材料质量波动可能影响产品稳定'
        },
        {
          type: '时间风险',
          level: 'info',
          description: '运输时间可能受天气影响产生波动'
        }
      ],
      pathAnalysis: [
        {
          description: '核心零件供应商 -> 机翼生产商 -> 机翼部件',
          length: 3,
          reliability: '87%'
        },
        {
          description: '核心零件供应商 -> 起落架生产商 -> 起落架部件',
          length: 3,
          reliability: '85%'
        },
        {
          description: '核心零件供应商 -> 发动机生产商 -> 发动机部件',
          length: 3,
          reliability: '83%'
        },
        {
          description: '核心零件供应商 -> 航电系统生产商 -> 电器部件生产商 -> 航电系统部件',
          length: 4,
          reliability: '75%'
        }
      ]
    };
  },
  mounted() {
    this.projectId = Number(localStorage.getItem('projectId'));
  },
  methods: {
    ...mapActions(['riskTransferQuery']),
    handleFirstLevelChange(value) {
      switch (value) {
        case 'structuralRisk':
          this.secondLevelOptions = [
            { label: '核心供应商', value: '核心供应商' },
            { label: '单一供应商', value: '单一供应商' },
            { label: '整体结构', value: '整体结构' }
          ];
          break;
        case 'operationalRisk':
          this.secondLevelOptions = [
            { label: '生产经营', value: '生产经营' },
            { label: '质量安全', value: '质量安全' },
            { label: '科技人才', value: '科技人才' }
          ];
          break;
        case 'environmentalRisk':
          this.secondLevelOptions = [
            { label: '技术封锁', value: '技术封锁' },
            { label: '政治冲突', value: '政治冲突' },
            { label: '区域热点', value: '区域热点' },
            { label: '自然灾害', value: '自然灾害' }
          ];
          break;
        default:
          this.secondLevelOptions = [];
      }
      this.secondLevelRisk = '';
    },
    // 点击按钮后显示分析结果
    // showAnalysisResults() {
    //   // 控制台输出指标
    //   console.log('一级指标：', this.firstLevelRisk);
    //   console.log('二级指标：', this.secondLevelRisk);
    //   // 向后端发起请求
    //
    //   //向GraphEditor组件发送请求
    //   this.$emit('showRiskChart', true);
    //   if (!this.startNode) {
    //     this.$message.warning('请输入预测风险节点');
    //     return;
    //   }
    //   this.showResults = true;
    // },
    async showAnalysisResults() {

      if (!this.startNode || !this.secondLevelRisk) {
        this.$message.warning('请输入预测风险节点并选择二级风险');
        return;
      }

      const scenarioMap = {
        // 结构风险
        '核心供应商': '核心供应商',
        '单一供应商': '质量安全',
        '整体结构': '核心供应商',

        // 运行风险
        '生产经营': '生产经营',
        '质量安全': '质量安全',
        '科技人才': '技术封锁',

        // 环境风险
        '技术封锁': '技术封锁',
        '政治冲突': '政治冲突',
        '区域热点': '区域热点',
        '自然灾害': '自然灾害'
      };

      const scenarioId = scenarioMap[this.secondLevelRisk];
      if (!scenarioId) {
        this.$message.warning('未知风险类型，请重新选择');
        return;
      }

      try {
        this.loading = true;
        this.errorMessage = '';

        const requestData = {
          scenario_id: scenarioId,
          enterprise: this.startNode,
          projectId: this.projectId
        };

        console.log('准备发送请求到后端API:', {
          url: 'http://localhost:5000/simulate',
          method: 'POST',
          data: requestData
        });

        // 发送实际请求
        const response = await axios.post('http://localhost:5000/simulate', requestData);

        if (response.data.code === 200) {
          console.log('后端返回数据:', response.data);
          this.processSimulationResults(response.data.data);
          this.$message.success('风险模拟成功');
        } else {
          throw new Error('服务器返回错误');
        }
      } catch (error) {
        this.errorMessage = '数据传输错误';
        this.$message.error(this.errorMessage);
        console.error('请求失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 处理从后端获取的模拟结果
    processSimulationResults(data) {
      // 显示结果面板
      this.showResults = true;

      // 清空旧数据
      this.riskAnalysis = [];
      this.pathAnalysis = [];

      // 处理失效企业列表，转换为风险分析格式
      const failedEnterprises = data.failed_enterprises || [];
      if (failedEnterprises.length > 0) {
        this.riskAnalysis.push({
          type: '供应链断裂风险',
          level: 'danger',
          description: `初始节点: ${data.start_enterprise}，共影响 ${failedEnterprises.length} 个企业`
        });

        // 添加路径分析（简化版，实际应基于图结构生成路径）
        // 先去重：避免起始节点重复出现在路径里
        // 先去掉和起点重复的
        const cleanedEnterprises = failedEnterprises.filter(e => e !== data.start_enterprise);

        let description;
        if (cleanedEnterprises.length === 0) {
          // 如果没有后续节点，就只显示起点
          description = data.start_enterprise;
        } else {
          // 否则拼接路径
          description = `${data.start_enterprise} -> ${cleanedEnterprises.slice(0, 3).join(' -> ')}${cleanedEnterprises.length > 3 ? ' -> ...' : ''}`;
        }

        this.pathAnalysis.push({
          description,
          length: cleanedEnterprises.length + 1,
          reliability: `${Math.max(100 - cleanedEnterprises.length * 10, 0)}%`
        });


      }

      // 添加风险描述
      this.riskAnalysis.push({
        type: data.scenario,
        level: 'warning',
        description: data.description
      });

      // 添加风险分析结论
      this.riskAnalysis.push({
        type: '风险分析结论',
        level: 'info',
        description: data.risk_analysis
      });

      // 如果后端返回了路径数据，使用它们
      if (data.paths && data.paths.length > 0) {
        this.pathAnalysis = data.paths;
      }
      this.riskData.startNode = this.startNode;
      this.riskData.failedEnterprises = failedEnterprises;
      console.log('RiskData:', this.riskData);
      // 触发图表更新
      this.$emit('showRiskChart', this.riskData);
    }
  }
};
</script>

<style scoped>
.search-container {
  margin: 20px 0;
  padding-bottom: 20px;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border: 1px solid #ebeef5;
  border-radius: 5px;

}
.search-title{
  text-align: center;
  margin: 20px 0;
}
.search-input {
  margin-bottom: 20px;
  text-align: center;
}
.input{
  width: 200px;
}
.search-node{
  width: 221px;
}

.search-button{
  text-align: center;
  display: block;
}
.input-title {
  font-weight: bold;
}



.analysis-info {
  margin-top: 20px;
}

.analysis-info .title {
  text-align: center;
  margin-bottom: 5px;
}

.risk-card,
.path-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.risk-item,
.path-item {
  margin-bottom: 15px;
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.risk-item:last-child,
.path-item:last-child {
  border-bottom: none;
}

.risk-description {
  margin-top: 5px;
}

.path-header {
  font-weight: bold;
  margin-bottom: 10px;
}

.path-metrics {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.path-content{
  font-size: 13px;
}
.risk-item .el-tag {
  margin-right: 10px;
}
</style>
